package com.jzr.medical.test.netty;

import com.jzr.netty.common.base.BaseMsg;
import com.jzr.netty.common.base.ConnectionException;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

public class LongConnectClient implements Runnable {
    private String host;
    private int port;

    Bootstrap bootstrap = null;
    NioEventLoopGroup group = null;
    SocketChannel channel = null;

    public LongConnectClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run() {
        try {
            bootstrap = new Bootstrap();
            group = new NioEventLoopGroup();

            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new ObjectEncoder(),
                                    new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                    new LongConnectHandler());
                        }
                    });

            // 发起异步连接操作
            ChannelFuture f = b.connect(host, port);
            f.awaitUninterruptibly();
            assert f.isDone();
            if (f.isSuccess()) {
                channel = (SocketChannel) f.channel();
                System.out.println("Connect Server Success!");
            } else {
                throw new ConnectionException("链接netty服务失败," + f.cause().getMessage());
            }
        }catch (Throwable e){
            e.printStackTrace();
        }finally {

        }
    }
    public void stop(){
        if(channel != null){
            channel.close();
            channel = null;
        }
        if(group != null){
            group.shutdownGracefully();
            group = null;
        }
    }
    public void send(BaseMsg request) throws Throwable {
        ChannelFuture f = channel.writeAndFlush(request).sync();
    }
}
